#!/usr/bin/php -q
<?php
require_once 'Zend/Db.php';
require_once 'Zend/Config/Ini.php';
class mkindex{
	private $config;
	function __construct(){
		$this->config = new Zend_Config(require '../../inc/dbcnf.php');
	}
	private function db(){
		return Zend_Db::factory($this->config->db_test);
	}
	public function test(){
		$r=$this->db()->fetchAll("select id,mol from compound");
		$fp = fopen($this->config->sdfpath. 'smartchem.sdf', 'w');
		$cnt = 0;
		// 每隔$limit行，刷新一下输出buffer，不要太大，也不要太小
		$limit = 100000;
		// 逐行取出数据，不浪费内存
		foreach($r as $row){
			$cnt ++;
			if ($limit == $cnt) { //刷新一下输出buffer，防止由于数据过多造成问题
				ob_flush();
				flush();
				$cnt = 0;
			}
			$sdf = str_replace("{#n#}", "\r\n", $row["mol"]);
			$sdf = $row["id"].$sdf;
			$sdf .= "\r\n>  <ID>\r\n".$row["id"]."\r\n";
			$sdf .= "\r\n$$$$\r\n";
			fputs($fp,$sdf);
		}
		fclose($fp);
		$r=system("diff ".$this->config->sdfpath. "smartchem.sdf ".$this->config->sdfpath. "smartchem.sdf.old");
		if($r){
			system("babel ".$this->config->sdfpath. 'smartchem.sdf' ." -ofs");
			system("cp ".$this->config->sdfpath."smartchem.sdf ". $this->config->sdfpath."smartchem.sdf.old" );
		}
	}
}
$obj = new mkindex();
while(true){
	$obj->test();	
	sleep(120);
}
